package main

import (
	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/testdata/protoexample"
	"log"
	"net/http"
	"strconv"
	"time"
)

type Book struct {
	Id     int
	Name   string
	Author string
}

func main() {
	r := gin.Default()
	//测试json
	r.GET("/jsonTest", func(c *gin.Context) {
		c.JSON(http.StatusOK, gin.H{
			"message": "jsonTest",
		})
	})
	//测试结构体转json
	r.GET("structTest", func(c *gin.Context) {
		idStr := c.DefaultQuery("id", "0")
		id, err := strconv.Atoi(idStr)
		if err != nil {
			c.JSON(http.StatusBadRequest, gin.H{
				"message": "error Id",
			})
			return
		}
		name := c.DefaultQuery("name", "小王子")
		author := c.DefaultQuery("author", "埃克苏佩")
		book := Book{id, name, author}
		c.JSON(http.StatusOK, book)
	})

	//xml返回
	r.GET("xmlTest", func(c *gin.Context) {
		book := Book{123, "小王子", "埃克苏佩"}
		c.XML(http.StatusOK, book)
	})

	//yaml返回
	r.GET("yamlTest", func(c *gin.Context) {
		data := map[string]interface{}{
			"name": "John",
			"age":  30,
		}
		c.YAML(http.StatusOK, data)
	})
	r.GET("/someProtoBuf", func(c *gin.Context) {
		reps := []int64{int64(1), int64(2)}
		// 定义数据
		label := "label"
		// 传protobuf格式数据
		data := &protoexample.Test{
			Label: &label,
			Reps:  reps,
		}
		c.ProtoBuf(200, data)
	})
	r.LoadHTMLGlob("D:/Projects/ginStudy/main/tem/*")
	r.GET("/index", func(c *gin.Context) {
		c.HTML(http.StatusOK, "index.html", gin.H{"title": "我是测试", "ce": "123456"})
		//c.Redirect(http.StatusOK, "https://cn.bing.com/")
	})

	r.GET("redirect", func(c *gin.Context) {
		c.Redirect(http.StatusMovedPermanently, "https://cn.bing.com/")
	})

	r.GET("/long_async", func(c *gin.Context) {
		//设置一个副本
		copyContext := c.Copy()
		/*	fmt.Println(copyContext)*/
		//异步处理
		go func() {
			for i := 0; i < 10; i++ {
				time.Sleep(3 * time.Second)
				log.Println("异步执行", copyContext.Request.URL.Path)
			}
		}()
	})

	// 2.同步
	r.GET("/long_sync", func(c *gin.Context) {
		for i := 0; i < 10; i++ {
			time.Sleep(3 * time.Second)
			log.Println("同步执行：" + c.Request.URL.Path)
		}
	})
	r.Run(":8888")

}
